package org.jeecg.modules.mobile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mobile")
public class MobileController {
    @Autowired
    private JdbcTemplate jdbc;

    //获取工单列表
    @GetMapping("/getOrders")
    public Result<?> getOrders(String state, String keyword, String isQuality) {
        String filter;

            String eq = state.equals("未完成") ? ">" : "<=";
            filter = "where a.num " + eq + " (select ifnull(sum(j.hnum), 0)+ifnull(sum(j.bnum), 0) from jobmat j where j.sgnumber= a.sgnumber) ";

        if (!StringUtils.isEmpty(keyword)) filter += "and a.sgnumber like '%" + keyword + "%'";
        String sql = "select a.*, c.cou,c.num1 from splan a  " +
                "left join (select count(*) cou,ifnull(sum(num), 0) as num1, sgnumber from jobmat group by sgnumber) c on a.sgnumber= c.sgnumber " + filter;
        System.out.println(sql);
        List<Map<String, Object>> l = jdbc.queryForList(sql);
        return Result.ok(l);
    }

    //获取工单信息
    @GetMapping("/getOrderInfo")
    public Result<?> getOrderInfo(String id) {
        String sql = "select a.*, c.num1, c.hnum, c.bnum as dnum, c.cou from splan a  " +
                "left join (select count(*) cou,ifnull(sum(num), 0) as num1,ifnull(sum(hnum), 0) as hnum,ifnull(sum(bnum), 0) as bnum,sgnumber from jobmat group by sgnumber) c on a.sgnumber = c.sgnumber " +
                "where a.id = '" + id + "'";
        List<Map<String, Object>> orders = jdbc.queryForList(sql);
        if (orders.isEmpty()) return Result.error("no data");
        JSONObject order = new JSONObject(orders.get(0));
        sql = "select * from splan where sgnumber= '" + order.getString("sgnumber") + "' order by create_time";
        List<Map<String, Object>> l = jdbc.queryForList(sql);
        JSONObject r = new JSONObject();
        r.put("order", order);
        r.put("missions", l);
        return Result.ok(r);
    }

    //获取用户信息
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(String username) {
        String sql = "select a.username, c.depart_name from sys_user a " +
                "left join sys_user_depart b on a.id = b.user_id " +
                "left join sys_depart c on b.dep_id = c.id " +
                "where username = '" + username + "'";
        List<Map<String, Object>> l = jdbc.queryForList(sql);
        if (l.isEmpty()) return Result.error("no user!");
        return Result.ok(l.get(0));
    }

    //获取工序信息
    @GetMapping("/getMissionInfo")
    public Result<?> getMissionInfo(String id) {
        String sql = "select a.id, a.fnumber, a.fname, a.gongxu, a.shebei, a.partcode, a.partname, a.sgnumber, a.wgzt, a.num, a.starttime, b.sum, b.hnum, b.bnum " +
                "from splan a left join (select sum(num) as sum, sgnumber, hnum, bnum from jobmat group by sgnumber) b on a.sgnumber = b.sgnumber " +
                "where a.id = '" + id + "'";
        List<Map<String, Object>> l = jdbc.queryForList(sql);
        if (l.isEmpty()) return Result.error("no data!");
        JSONObject m = new JSONObject(l.get(0));
        String fnumber = m.getString("fnumber");
        sql = "select a.*, b.num, b.hnum, b.dnum from sporder a left join gxcp b on a.id = b.sporderid where a.fnumber = '" + fnumber + "'";
        l = jdbc.queryForList(sql);
        JSONObject o = new JSONObject();
        if (!l.isEmpty()) o = new JSONObject(l.get(0));
        JSONObject r = new JSONObject();
        r.put("mission", m);
        r.put("order", o);
        return Result.ok(r);
    }

    //获取工序列表
    @GetMapping("/getMissions")
    public Result<?> getMissions(String state, String keyword) {
        keyword = StringUtils.isEmpty(keyword) ? "" : keyword;
        String filter = "where a.sgnumber like '%" + keyword + "%'";
        switch (state) {
            case "未开工":
                filter += " and (a.wgzt = '未开工' or a.wgzt is null)";
                break;
            case "已开工":
                filter += " and a.wgzt = '已开工'";
                break;
            case "未报工":
                filter += " and ifnull(b.sum,0) < a.num";
                break;
            case "待报工":
                filter += " and ifnull(b.sum,0) < a.num";
                break;
            case "完成":
                filter += " and b.sum is not null and ifnull(b.sum,0) = a.num";
                break;
        }
        String sql = "select a.id, a.fnumber, a.fname, a.gongxu, a.sgnumber, a.create_by, a.create_time, a.wgzt, a.num, b.sum, c.luxian, c.kgstart, c.kgend " +
                "from splan a left join (select sum(num) as sum, sgnumber from jobmat group by sgnumber) b on a.sgnumber = b.sgnumber " +
                "left join sporder c on a.fnumber = c.fnumber " + filter;
        System.out.println("工单任务"+sql);
        return Result.ok(jdbc.queryForList(sql));
    }

    //开工
    @GetMapping("/goWork")
    public Result<?> goWork(String missionId) {
        boolean a = jdbc.update("update splan set wgzt = '已开工' where id = ? and (wgzt = '未开工' or wgzt is null)", missionId) > 0;
        return a ? Result.ok("成功!") : Result.error("已开工或工序不存在!");
    }

    //获取工序报工记录
    @GetMapping("/getProcessRecords")
    public Result<?> getProcessRecords(String sgnumber) {
        String sql = "select * from jobmat where sgnumber = '" + sgnumber + "'";
        return Result.ok(jdbc.queryForList(sql));
    }

    //popup报工人员列表
    @GetMapping("/getMembers")
    public Result<?> getMembers() {
        String sql = "select a.id, a.username, a.realname, ifnull(c.depart_name, '-') as dname from sys_user a " +
                "left join sys_user_depart b on a.id = b.user_id " +
                "left join sys_depart c on b.dep_id = c.id";
        List<Map<String, Object>> l = jdbc.queryForList(sql);
        JSONArray r = new JSONArray();
        for (Map<String, Object> m : l) {
            String dname = (String) m.get("dname");
            int a = -1;
            for (int i = 0; i < r.size(); i++) {
                if (r.getJSONObject(i).getString("text").equals(dname)) {
                    a = i;
                    break;
                }
            }
            if (a > -1) {
                JSONObject j = r.getJSONObject(a);
                JSONArray array = j.getJSONArray("children");
                array.add(m.get("realname"));
                j.put("children", array);
                r.set(a, j);
            } else {
                JSONObject j = new JSONObject();
                j.put("text", dname);
                JSONArray array = new JSONArray();
                array.add(m.get("realname"));
                j.put("children", array);
                r.add(j);
            }
        }
        return Result.ok(r);
    }

    //生产报工
    @PostMapping("/submitWork")
    public Result<?> submitWork(@RequestBody JSONObject json, HttpServletRequest request) {
        JSONObject mission = json.getJSONObject("mission");
        JSONArray records = json.getJSONArray("records");
        String username = JwtUtil.getUserNameByToken(request);
        String sqlBase = "insert into jobmat(id, create_by, create_time, gxmc, shebei, kgtime, wgtime, fnumber, partcode, wlmc, num, bnum, hnum, banci, sgnumber, shengchanren) " +
                "values (uuid(), '%s', now(), '%s', '%s', '%s', now(), '%s', '%s', '%s', '%s', '0', '0', '早班', '%s', '%s')";
        int a = 0;
        for (int i = 0; i < records.size(); i++) {
            JSONObject rec = records.getJSONObject(i);
            String sql = String.format(sqlBase, username, mission.getString("gongxu"), mission.getString("shebei"),
                    mission.getString("starttime"), mission.getString("fnumber"), mission.getString("partcode"),
                    mission.getString("partname"), rec.getString("c"), mission.getString("sgnumber"), rec.getString("b"));
            a += jdbc.update(sql);
        }
        return a > 0 ? Result.ok("成功") : Result.error("失败");
    }

    //获取工单报工记录
    @GetMapping("/getOrderJob")
    public Result<?> getOrderJob(String fnumber, String keyword, String id) {
        String sql = "select a.id, a.gxmc, a.create_by, a.create_time, a.shebei, a.fnumber, a.wlmc, a.num, a.bnum, a.hnum, a.shengchanren, a.choujian, a.sgnumber, b.fname, b.leader, c.luxian, c.partcode " +
                "from jobmat a left join splan b on a.sgnumber = b.sgnumber " +
                "left join sporder c on a.fnumber = c.fnumber ";
        String filter = "where a.sgnumber = '" + fnumber + "' and b.fname like '%" + keyword + "%'";
        if (StringUtils.isNotEmpty(id)) {
            filter = "where a.id = '    " + id + "'";
        }
        return Result.ok(jdbc.queryForList(sql + filter));
    }

    //质检报工
    @PostMapping("/submitQuality")
    public Result<?> submitQuality(@RequestBody JSONObject json, HttpServletRequest request) {
        String username = JwtUtil.getUserNameByToken(request);
        String sql = "insert into sqcdan(id, create_by, create_time, fnumber, gnumber, gname, jianyanleixing, partcode, wlmc, gxmc, num, zzr, jianyanyuan, jianyantime, hnum, bhnum, `status`, rangbu, jobmatid, sgnumber) " +
                "values (uuid(), '%s', now(), 'JY%d', '%s', '%s', '工序检验', '%s', '%s', '%s', '%s', '%s', '%s', now(), '%s', '%s', '未处理', '0', '%s', '%s')";
        sql = String.format(sql, username, new Date().getTime(), json.getString("fnumber"), json.getString("fnumber"),
                json.getString("partcode"), json.getString("wlmc"), json.getString("gxmc"),
                json.getString("num"), json.getString("leader"), json.getString("jianyanyuan"),
                json.getString("hnum"), json.getString("bhnum"), json.getString("id"), json.getString("sgnumber"));
        int a = jdbc.update(sql);
        if (a > 0) {
            sql = "update jobmat set hnum = hnum + %d, bnum = bnum + %d where id = '%s'";
            sql = String.format(sql, json.getInteger("hnum"), json.getInteger("bhnum"), json.getString("id"));
            a = jdbc.update(sql);
        }
        return a > 0 ? Result.ok("成功") : Result.error("失败");
    }

    //首页数字
    @GetMapping("/getHomeNumbers")
    public Result<?> getHomeNumbers() {
        Object []r = {0, 0, 0, 0};

        String sql = "select count(*) from splan where wgzt = '未开工' or wgzt is null";
        r[1] = jdbc.query(sql, (resultSet, i) -> {
            Object count = resultSet.getObject("count(*)");
            return count == null ? 0 : count;
        }).get(0);

        sql = "select count(*) from splan a where a.num != ifnull((select sum(b.num) from jobmat b where b.sgnumber = a.sgnumber), 0)";
        r[2] = jdbc.query(sql, (resultSet, i) -> {
            Object count = resultSet.getObject("count(*)");
            return count == null ? 0 : count;
        }).get(0);

        sql = "select count(*) from sporder a left join gxcp b on a.id = b.sporderid " +
                "where b.num != (select ifnull(sum(c.hnum), 0) from jobmat c where c.fnumber = a.fnumber)";
        r[3] = jdbc.query(sql, (resultSet, i) -> {
            Object count = resultSet.getObject("count(*)");
            return count == null ? 0 : count;
        }).get(0);

        return Result.ok(r);
    }

    //获取通知
    @GetMapping("/getMsg")
    public Result<?> getMsg() {
        return Result.ok(jdbc.queryForList("select * from" +
                "    (select a.id, concat('/missionInfo?id=', a.id) as path, starttime, 0 as flag from splan a where a.wgzt != '已开工'" +
                "    union select b.id, concat('/qualityRP?id=', b.id), create_time, 1 from jobmat b where num != b.hnum) t " +
                "order by starttime desc"));
    }
}
